package com.godofball.medtrack.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.godofball.medtrack.common.CurrentUser;
import com.godofball.medtrack.exception.PurchaseException;
import com.godofball.medtrack.mapper.PurchaseMapper;
import com.godofball.medtrack.pojo.Manufacturer;
import com.godofball.medtrack.pojo.Purchase;
import com.godofball.medtrack.pojo.PurchaseDetail;
import com.godofball.medtrack.service.ManufacturerService;
import com.godofball.medtrack.service.PurchaseDetailService;
import com.godofball.medtrack.service.PurchaseService;
import com.godofball.medtrack.service.WarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
public class PurchaseServiceImpl extends ServiceImpl<PurchaseMapper, Purchase>implements PurchaseService {

    @Autowired
    private ManufacturerService manufacturerService;

    @Autowired
    private WarehouseService warehouseService;

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Override
    @Transactional
    public void generatePurchase(Long manufacturerId, String remark) {
        Manufacturer manufacturer = manufacturerService.getById(manufacturerId);
        if (manufacturer==null) throw new PurchaseException("产商不存在");

        //找出要进货的药品
        LambdaQueryWrapper<PurchaseDetail> purchaseDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        purchaseDetailLambdaQueryWrapper.eq(PurchaseDetail::getAdminId, CurrentUser.getCurrentUser());
        purchaseDetailLambdaQueryWrapper.isNull(PurchaseDetail::getPurchaseId);
        List<PurchaseDetail> purchaseDetails = purchaseDetailService.list(purchaseDetailLambdaQueryWrapper);

        if (purchaseDetails.size()==0||purchaseDetails==null) throw new PurchaseException("进货药品为空");

        Purchase purchase = new Purchase();
        purchase.setRemark(remark);
        purchase.setStatus(1);
        purchase.setManufacturerId(manufacturerId);

        Integer totalCount=0;
        BigDecimal totalPrice=new BigDecimal(0);

        for (PurchaseDetail purchaseDetail : purchaseDetails) {
            totalCount+=purchaseDetail.getPurchaseCount();
            totalPrice=totalPrice.add(purchaseDetail.getTotalPrice());
        }
        purchase.setTotalPrice(totalPrice);
        purchase.setTotalCount(totalCount);

        //保存进货表单，主要是为了获取自动生成的id
        this.save(purchase);

        //为每个进货单表项赋进货单号，并保存
        purchaseDetails.forEach(purchaseDetail -> purchaseDetail.setPurchaseId(purchase.getId()));
        purchaseDetailService.updateBatchById(purchaseDetails);

        warehouseService.save(purchase,purchaseDetails);

    }
}
